package com.alan.api.util;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by Alan on 2017/11/3.
 */
public class Mvc2Utils {

    // -- header 常量定义 --//
    private static final String HEADER_ENCODING = "encoding";
    private static final String HEADER_NOCACHE = "no-cache";
    private static final String DEFAULT_ENCODING = "UTF-8";
    private static final boolean DEFAULT_NOCACHE = true;
    private static final long EXPIRES_SECONDS = 3600L;// 缓存时间(单位为秒)

    /**
     * 取得HttpSession的简化函数.
     */
    public static HttpSession getSession() {
        return getRequest().getSession();
    }

    /**
     * 取得HttpSession的简化函数.
     */
    public static HttpSession getSession(boolean isNew) {
        return getRequest().getSession(isNew);
    }

    /**
     * 取得HttpSession中Attribute的简化函数.
     */
    public static Object getSessionAttribute(String name) {
        HttpSession session = getSession(false);
        return (session != null ? session.getAttribute(name) : null);
    }

    /**
     * 取得HttpRequest的简化函数.
     */
    public static HttpServletRequest getRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        return request;
    }

    public static String getRequestURI() {
        String requestUri = (String) getRequest().getAttribute("javax.servlet.forward.request_uri");
        if (requestUri == null) {
            return getRequest().getRequestURI();
        }
        return requestUri;
    }

    /**
     * 取得HttpRequest中Parameter的简化方法.
     */
    public static String getParameter(String name) {
        return getRequest().getParameter(name);
    }

}
